load('application');

before(loadVote, {only: ['show', 'edit', 'update', 'destroy']});

action('new', function () {
    this.title = 'New vote';
    this.vote = new Vote;
    render();
});

action(function create() {
    Vote.create(req.body.Vote, function (err, vote) {
        if (err) {
            flash('error', 'Vote can not be created');
            render('new', {
                vote: vote,
                title: 'New vote'
            });
        } else {
            flash('info', 'Vote created');
            redirect(path_to.votes());
        }
    });
});

action(function index() {
    this.title = 'Votes index';
    Vote.all(function (err, votes) {
        render({
            votes: votes
        });
    });
});

action(function show() {
    this.title = 'Vote show';
    render();
});

action(function edit() {
    this.title = 'Vote edit';
    render();
});

action(function update() {
    this.vote.updateAttributes(body.Vote, function (err) {
        if (!err) {
            flash('info', 'Vote updated');
            redirect(path_to.Vote(this.Vote));
        } else {
            flash('error', 'Vote can not be updated');
            this.title = 'Edit vote details';
            render('edit');
        }
    }.bind(this));
});

action(function destroy() {
    this.vote.destroy(function (error) {
        if (error) {
            flash('error', 'Can not destroy vote');
        } else {
            flash('info', 'Vote successfully removed');
        }
        send("'" + path_to.votes() + "'");
    });
});

function loadVote() {
    Vote.find(params.id, function (err, vote) {
        if (err || !vote) {
            redirect(path_to.votes());
        } else {
            this.vote = vote;
            next();
        }
    }.bind(this));
}
